import React, { useEffect, useRef, useState } from 'react'
import { Checkbox, Form, Radio } from 'antd'
import useGetTableData from '@/hooks/useGetTableDataV2'
import {
  getNewArrivalSpeedListBySpu,
  getSummarySupplementSpeedListBySpu,
  getSummaryReorderSpeedListBySpu,
} from '@/api/monitor'
import SearchForm from '@/components/CustomForm/SearchForm'
import { useForm } from 'antd/es/form/Form'
import PageContainer from '@/components/PageContainer'
import { useOneSpuColumns, useTwoSpuColumns, useThreeSpuColumns } from '../TableColumns'
import { DashBoardTimeAchieveVO as ITableData } from '../types'
import CustomTable from '@/components/QsfCustomTable'
import { useAppSelector } from '@/store/hooks'
import { searchConfig } from '../FormConfig'
import '../index.less'
import useCachePage from '@/hooks/useCachePage'
import useGetProDevSeason from '@/hooks/useGetProDevSeason'
import useGetClassIds from '@/hooks/useGetClassIds'
import { useSearchParams } from 'react-router-dom'
import { getProductClassConfigByType } from '@/api/goods'
const ClassNameToIdMap: Record<string, string> = {
  家居服: '123',
  内衣: '124',
  袜子: '125',
  小裤: '126',
  文胸: '127',
  床上用品: '128',
  成衣: '138',
  鞋类: '1706',
  童装: '2327',
}
const Index: React.FC = () => {
  const [form] = useForm()
  const [FormMonitor] = useForm()
  const DICTDATA = useAppSelector((state) => state.login.DICTDATA)
  const ProDevSeason = useGetProDevSeason()
  const tinyClassIdsRef = useRef<string[]>([])
  const [classBig, setclassBig] = useState<IOptionItem[]>([])
  const { classIdOptions, tinyClassIds, settinyClassIds, handleClassIdChange, getIdsByBigClassId } = useGetClassIds()
  const [currentSelectKeys, setcurrentSelectKeys] = useState<number[]>([])
  const [query] = useSearchParams()
  const dimension = query.get('dimension') || null
  const diffKeys = useRef<number[]>([])
  // 排序规则，0按到仓时间，1按总周期  sortRule
  const sortRule = useRef<0 | 1>(0)
  // 0 正序 1 倒序
  const sortType = useRef<0 | 1>(1)
  const orderMap: Record<string, any> = {
    warehouseTime: 0,
    totalCycle: 1,
  }
  useEffect(() => {
    diffKeys.current.includes(0) && search()
    diffKeys.current.includes(1) && searchV1()
    diffKeys.current.includes(2) && searchV2()
  }, [diffKeys.current])
  useEffect(() => {
    tinyClassIdsRef.current = tinyClassIds
  }, [tinyClassIds])
  const { setCachePage, getCachePage } = useCachePage('/monitor/fulllink/list?type=spu')
  const { tableProps, params, search, reset, reload } = useGetTableData<ITableData>(getNewArrivalSpeedListBySpu, {
    form: form,
    immediatelySend: false,
    defaultFieldsParams: {
      isMainProduct: 1,
    },
    paramsCallback: (reqParams) => {
      return {
        ...reqParams,
        sortRule: sortRule.current,
        sortType: sortType.current,
        fineClassIdList: tinyClassIdsRef.current.length > 0 ? tinyClassIdsRef.current : null,
      }
    },
  })
  const {
    tableProps: tablePropsV1,
    search: searchV1,
    reset: resetV1,
    reload: reloadV1,
  } = useGetTableData<ITableData>(getSummarySupplementSpeedListBySpu, {
    form: form,
    immediatelySend: false,
    defaultFieldsParams: {
      isMainProduct: 1,
    },
    paramsCallback: (reqParams) => {
      return {
        ...reqParams,
        sortRule: sortRule.current,
        sortType: sortType.current,
        fineClassIdList: tinyClassIdsRef.current.length > 0 ? tinyClassIdsRef.current : null,
      }
    },
  })
  const {
    tableProps: tablePropsV2,
    search: searchV2,
    reset: resetV2,
    reload: reloadV2,
  } = useGetTableData<ITableData>(getSummaryReorderSpeedListBySpu, {
    form: form,
    immediatelySend: false,
    defaultFieldsParams: {
      isMainProduct: 1,
    },
    paramsCallback: (reqParams) => {
      return {
        ...reqParams,
        sortRule: sortRule.current,
        sortType: sortType.current,
        fineClassIdList: tinyClassIdsRef.current.length > 0 ? tinyClassIdsRef.current : null,
      }
    },
  })
  useEffect(() => {
    getProductClassConfig()
  }, [])
  useEffect(() => {
    if (ProDevSeason && ProDevSeason.length > 0) {
      handleCacheData()
    }
  }, [ProDevSeason])
  useEffect(() => {
    if (dimension && classIdOptions.length > 0) {
      form.resetFields()
      const bigClassId = ClassNameToIdMap[dimension]
      if (!bigClassId) return
      const tinyClassIds = getIdsByBigClassId(bigClassId)
      tinyClassIdsRef.current = tinyClassIds
      settinyClassIds(tinyClassIds)
      form.setFieldsValue({
        isMainProduct: 1,
        tinyClassIds: [bigClassId],
      })
      setcurrentSelectKeys([0, 1, 2])
      FormMonitor.setFieldValue('selectKeys', [0, 1, 2])
      reload({ current: 1, size: 10, tinyClassIds: [bigClassId], isMainProduct: 1 })
      reloadV1({ current: 1, size: 10, tinyClassIds: [bigClassId], isMainProduct: 1 })
      reloadV2({ current: 1, size: 10, tinyClassIds: [bigClassId], isMainProduct: 1 })
      setCachePage({
        ...params,
        selectKeys: [0, 1, 2],
        isMainProduct: 1,
        tinyClassIds: [bigClassId],
        cachedtinyClassIds: tinyClassIds,
      })
    }
  }, [dimension, classIdOptions])
  const handleCacheData = async () => {
    if (dimension) return
    const cacheData = getCachePage()
    if (cacheData == null) {
      await form.validateFields()
      search()
      searchV1()
      searchV2()
      setCachePage({ ...params, selectKeys: [0, 1, 2] })
      setcurrentSelectKeys([0, 1, 2])
    } else {
      form.resetFields()
      const { selectKeys, cachedtinyClassIds, ...resetCacheData } = cacheData
      if (cacheData.tinyClassIds && cacheData.tinyClassIds.length > 0) {
        tinyClassIdsRef.current = cachedtinyClassIds
        settinyClassIds(cachedtinyClassIds)
      }
      form.setFieldsValue({
        ...resetCacheData,
      })
      setcurrentSelectKeys(selectKeys || [])
      FormMonitor.setFieldValue('selectKeys', selectKeys || [])
      selectKeys?.includes(0) && reload({ ...resetCacheData })
      selectKeys?.includes(1) && reloadV1({ ...resetCacheData })
      selectKeys?.includes(2) && reloadV2({ ...resetCacheData })
    }
  }
  const handleTableChange = (_: any, __: any, sorter: any) => {
    sortRule.current = orderMap[sorter?.field] != undefined ? orderMap[sorter?.field] : 0
    sortType.current = sorter?.order === 'ascend' ? 0 : sorter?.order === 'descend' ? 1 : 0
    currentSelectKeys.includes(0) && search()
    currentSelectKeys.includes(1) && searchV1()
    currentSelectKeys.includes(2) && searchV2()
  }
  const getProductClassConfig = async (type: 1 | 2 | 3 | 4 = 1) => {
    const res = await getProductClassConfigByType<{
      className: string
      classConfigId: string | number
    }>({ type, auth: 1 })
    const classIdOptions =
      res?.data?.map((item) => {
        return {
          label: item.className,
          value: item.classConfigId,
        }
      }) || []
    setclassBig(classIdOptions)
  }
  return (
    <PageContainer className="monitor_fulllink_wrap">
      <SearchForm
        params={params}
        form={form}
        searchConfig={searchConfig({
          DICTDATA,
          ProDevSeason,
          classIdOptions,
          handleClassIdChange,
          settinyClassIds,
          classBig,
        })}
        onFinish={async () => {
          currentSelectKeys.includes(0) && search()
          currentSelectKeys.includes(1) && searchV1()
          currentSelectKeys.includes(2) && searchV2()
          setCachePage({
            ...form.getFieldsValue(),
            selectKeys: currentSelectKeys,
            cachedtinyClassIds: tinyClassIds,
            current: 1,
            size: 10,
          })
        }}
        onReset={() => {
          FormMonitor.setFieldValue('selectKeys', [0, 1, 2])
          setcurrentSelectKeys([0, 1, 2])
          tinyClassIdsRef.current = []
          setCachePage({ selectKeys: [0, 1, 2], current: 1, size: 10 })
          currentSelectKeys.includes(0) && reset()
          currentSelectKeys.includes(1) && resetV1()
          currentSelectKeys.includes(2) && resetV2()
        }}
        extra={
          <div className="table_extra_flex_wrapbox">
            <div className="table_extra_flex">
              <Form form={FormMonitor} className="suggestion_form" initialValues={{ selectKeys: [0, 1, 2] }}>
                <span style={{ fontWeight: 800, marginRight: 8 }}>时效监控：</span>
                <Form.Item noStyle name="selectKeys">
                  <Checkbox.Group
                    onChange={(selectKeys) => {
                      const diff = selectKeys.filter((item) => !currentSelectKeys?.includes(item))
                      diffKeys.current = diff
                      const cacheData = getCachePage()
                      setcurrentSelectKeys(selectKeys)
                      setCachePage({
                        ...cacheData,
                        selectKeys,
                        current: 1,
                        size: 10,
                      })
                    }}
                    options={[
                      {
                        label: '上新时效',
                        value: 0,
                      },
                      {
                        label: '现采补充款时效',
                        value: 1,
                      },
                      {
                        label: '返单全链路时效',
                        value: 2,
                      },
                    ]}
                  />
                </Form.Item>
              </Form>
            </div>
            <div className="table_extra_flex"></div>
          </div>
        }
      ></SearchForm>
      {currentSelectKeys.includes(0) ? (
        <div className="fulllink_table_box">
          <div className="rtb_title">上新时效</div>
          <div className="rtb_main">
            <CustomTable
              className="mini_table_custom_style"
              stripe={false}
              isAutoScrollY={false}
              columns={useOneSpuColumns()}
              {...tableProps}
              rowKey={(rows) => rows.dimension}
              onChange={handleTableChange}
            />
          </div>
        </div>
      ) : null}
      {currentSelectKeys.includes(1) ? (
        <div className="fulllink_table_box">
          <div className="rtb_title">现采补充款时效</div>
          <div className="rtb_main">
            <CustomTable
              className="mini_table_custom_style"
              stripe={false}
              isAutoScrollY={false}
              columns={useTwoSpuColumns()}
              {...tablePropsV1}
              rowKey={(rows) => rows.dimension}
              onChange={handleTableChange}
            />
          </div>
        </div>
      ) : null}
      {currentSelectKeys.includes(2) ? (
        <div className="fulllink_table_box">
          <div className="rtb_title">返单全链路时效</div>
          <div className="rtb_main">
            <CustomTable
              className="mini_table_custom_style"
              stripe={false}
              isAutoScrollY={false}
              columns={useThreeSpuColumns()}
              {...tablePropsV2}
              rowKey={(rows) => rows.dimension}
              onChange={handleTableChange}
            />
          </div>
        </div>
      ) : null}
    </PageContainer>
  )
}

export default Index
